// pages/record/record.js
// var util = require("../../../../utils/util.js");
//获取应用实例
const app = getApp()
// var wxCharts = require('../../../../utils/wxcharts.js');
var windowWidth = 320;
var chart_array = {};
// var lineChart = null;
// let filter = require('../../../../utils/filter.js');
// filter.loginFilter
Page(({
  canvasIdErrorCallback: function (e) {
    console.error(e.detail.errMsg)
  },
  /**
   * 页面的初始数据
   */
  data: {
    index:0,
    empty:false,
    hasUserInfo:false,
    userInfo:null,
    canvas_map_datas:{},
    name:'',
    times: []
  },
  // touchHandler: function (e) {// 图表事件
  //   console.log(lineChart.getCurrentDataIndex(e));
  //   lineChart.showToolTip(e, {
  //     // background: '#7cb5ec',
  //     format: function (item, category) {
  //       return category + item.data
  //     }
  //   });
  // },
  getData: async function (){
    wx.showLoading({
      title: '加载中...',
    })
    var res = await wx.cloud.callFunction({
      name: "record",
      data: {
        action: "list"
      }
    })
    var records = res.result;
    let times = []
    for(var i in records){
      let data = records[i].records
      for(var k in data){
        // times.push(util.formatTime_chinese(new Date(data[k].create_time)))
        this.setData({
          times : times
        })
      }
    }
    for (var evaluation_id in records) {
      var latest_date = records[evaluation_id].latest_date;
      var latest_date_text = null;
      if(latest_date){
        latest_date_text = util.formatTime_chinese(new Date(latest_date));
      }
      records[evaluation_id].latest_date_text = latest_date_text;
      if(records[evaluation_id].records.length>0){
        records[evaluation_id].selected_dimension_id = records[evaluation_id].records[0].results[0].dimension_id;
        records[evaluation_id].from_index = records[evaluation_id].records.length > 3 ? records[evaluation_id].records.length - 3 : 0;
        if (records[evaluation_id].from_index == 0){
          records[evaluation_id].from_class="disabled";
        }else{
          records[evaluation_id].from_class = "";
        }
        records[evaluation_id].end_index = records[evaluation_id].records.length;
      }
    }
    
    if (Object.keys(records).length === 0) {
      this.setData({
        empty: true
      })
    }else{
      this.setData({
        empty: false
      })
    }
    this.setData({
      records: records,
      // year: year,
      // month:month
    })
    if (this.data.empty) {
      this.setData({
        canvas_map_datas: {}
      })
      wx.hideLoading()
      return false;
    }
    //获取颜色
    var colorMaps = {};
    for (var evaluation_id in records) {
      var map = {};
      var scales = records[evaluation_id].scales;
      for (var i = 0; i < scales.length; ++i) {
        map[scales[i].scales_id] = scales[i].color;
      }
      colorMaps[evaluation_id] = map;
    }

    // 创建图表
    var canvas_map_datas = {};
    for (var evaluation_id in records) {//此处evaluation_id是主题测评id
      var evaluation_item = records[evaluation_id];
      var tmprecords = evaluation_item.records;
      if(tmprecords.length == 0){
        continue;
      }
      var canvas_map = {};
      for (var i = tmprecords.length - 1; i >= 0; --i) {
        var item = tmprecords[i];
        var tt = util.formatDate_chinese_monthdate(new Date());
        var dimensions_results = item.results;
        for(var k = 0 ; k < dimensions_results.length ; ++k){
          var tmpDimensionResult = dimensions_results[k];
          var tmp_dimension_id = tmpDimensionResult.dimension_id;
          if (canvas_map[tmp_dimension_id] == undefined){
            var canvas_data = {};
            canvas_data.categories = [];
            canvas_data.data = [];
            // canvas_data.circle = [];
            canvas_data.categories.push(tt);
            canvas_data.color = colorMaps[evaluation_id][tmpDimensionResult.scales_id];
            canvas_data.data.push(tmpDimensionResult.result.score);
            //     if (!tmpDimensionResult.important) {//是否附加结果
            //       canvas_data.circle.push(3);
            //     } else {
            //       canvas_data.circle.push(6);
            //     }
            canvas_map[tmp_dimension_id] = canvas_data;
          }else{
            var canvas_data = canvas_map[tmp_dimension_id];
            canvas_data.categories.push(tt);
            canvas_data.data.push(tmpDimensionResult.result.score);
            //     if (!tmpDimensionResult.important) {//是否附加结果
            //       canvas_data.circle.push(3);
            //     } else {
            //       canvas_data.circle.push(6);
            //     }
            canvas_map[tmp_dimension_id] = canvas_data;
          }
        }
      }
      canvas_map_datas[evaluation_id] = canvas_map;
    }
    this.setData({
      canvas_map_datas: canvas_map_datas
    })
    chart_array = {};
    for (var evaluation_id in canvas_map_datas) {
      var canvas_id = "lineCanvas_" + evaluation_id;
      if (chart_array[evaluation_id] == undefined) {
        var tmp_canvas_data = canvas_map_datas[evaluation_id][records[evaluation_id].selected_dimension_id];
        var from_index = records[evaluation_id].from_index;
        var end_index = records[evaluation_id].end_index;
        let tmp = {};
        tmp.color = tmp_canvas_data.color;
        tmp.categories = tmp_canvas_data.categories.slice(from_index, end_index);
        tmp.data = tmp_canvas_data.data.slice(from_index, end_index);
        var tmpcanvas = this.createCanvas(canvas_id, tmp , windowWidth);
        chart_array[evaluation_id] = tmpcanvas;
      }else{
        this.updateData(evaluation_id);
      }
    }
    // this.setData({
    //   chart_array: chart_array
    // })
    wx.hideLoading()
  },
  //更新图表数据
  updateData: function (evaluation_id,canvas_data){
    var records = this.data.records;
    var from_index = records[evaluation_id].from_index;
    var end_index = records[evaluation_id].end_index;
    var chart = chart_array[evaluation_id];
    if(!chart){
      return ;
    }
    if(canvas_data == undefined){
      canvas_data = this.data.canvas_map_datas[evaluation_id][this.data.records[evaluation_id].selected_dimension_id];
    }
    var tmp = {};
    tmp.color = canvas_data.color;
    tmp.categories = canvas_data.categories.slice(from_index,end_index);
    tmp.data = canvas_data.data.slice(from_index, end_index);
    chart.updateData({
      categories: tmp.categories,
      series: [{
        name: '',
        color: tmp.color,
        data: tmp.data,
        // circle: canvas_data.circle,
        format: function (val, name) {
          return val + '分';
        }
      }],
    });
  },
  leftfunc:function(e){
    var evaluation_id = e.currentTarget.dataset.evaluation_id;
    var records = this.data.records;
    var from_index = records[evaluation_id].from_index;
    if (from_index == 0){
      return false;
    }
    records[evaluation_id].from_index = from_index - 1;
    if (records[evaluation_id].from_index == 0) {
      records[evaluation_id].from_class = "disabled";
    } else {
      records[evaluation_id].from_class = "";
    }
    this.setData({records:records})
    var canvas_data = this.data.canvas_map_datas[evaluation_id][this.data.records[evaluation_id].selected_dimension_id];
    this.updateData(evaluation_id,canvas_data);
  },
  rightfunc: function (e) {
    return false;
  },
  dimensionchangefunc:function(e){
    var evaluation_id = e.currentTarget.dataset.evaluation_id;
    var dimension_id = e.currentTarget.dataset.dimension_id;
    var records = this.data.records;
    records[evaluation_id].selected_dimension_id = dimension_id;
    this.setData({
      records:records
    })
    this.updateData(evaluation_id)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    // if (app.globalData.userInfo) {//若已登陆
      var userInfo = app.globalData.userInfo;
      this.setData({
        userInfo: userInfo,
        hasUserInfo: true,
        name: options.id
      })
      try {
        var res = wx.getSystemInfoSync();
        windowWidth = res.windowWidth - 32;//减掉的是容器的左右padding
      } catch (e) {
        console.error('getSystemInfoSync failed!');
      }
      //获取档案数据
      //获取最近一次测评记录的年月
      this.getData();
    // }else{//若没有登陆，则跳转到统一授权登陆页面
    //   // app.autologin(null,null)
    // }
  },
  createCanvas(canvas_id, canvas_data,windowWidth){
    if (canvas_data.data.length == 0){
      return null;
    }
    // console.log(canvas_data)
    // var lineChart = new wxCharts({
    //   canvasId: canvas_id,
    //   type: 'line',
    //   categories: canvas_data.categories,
    //   animation: false,
    //   legend: false,
    //   // background: '#f5f5f5',
    //   series: [{
    //     name: '',
    //     color:canvas_data.color,
    //     data: canvas_data.data,
    //     // circle: canvas_data.circle,
    //     format: function (val, name) {
    //       return val + '分';
    //     }
    //   }],
    //   xAxis: {//是否隐藏x轴分割线
    //     disableGrid: true
    //   },
    //   yAxis: {//y轴数据
    //     // format: function (val) {
    //     //   return val.toFixed(2);
    //     // },
    //     min: 0,
    //     // disabled:true
    //   },
    //   width: windowWidth,
    //   height: 216,
    //   // transform: scale(0.5),
    //   dataLabel: false,//是否在图表上直接显示数据
    //   dataPointShape: true,//是否在图标上显示数据点标志
    //   extra: {
    //     lineStyle: 'straight'
    //   }
    // });
    // return lineChart;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // if (app.globalData.userInfo) {//若已登陆
    //   var userInfo = app.globalData.userInfo;
    //   userInfo.pre_born_date_text = util.formatDate_chinese(new Date(userInfo.pre_born_date));
    //   this.setData({
    //     userInfo: userInfo,
    //     hasUserInfo: true
    //   })
    // }
    // if (app.globalData.userInfo) {//若已登陆
    // var userInfo = app.globalData.userInfo;
    // this.setData({
    //   userInfo: userInfo,
    //   hasUserInfo: true
    // })
    // try {
    //   var res = wx.getSystemInfoSync();
    //   windowWidth = res.windowWidth - 32;//减掉的是容器的左右padding
    // } catch (e) {
    //   console.error('getSystemInfoSync failed!');
    // }
    // //获取档案数据
    // //获取最近一次测评记录的年月
    // this.getData();
  // }else{//若没有登陆，则跳转到统一授权登陆页面
  //   // app.autologin(null,null)
  // }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    if (this.data.hasUserInfo) {//若已登陆
      try {
        var res = wx.getSystemInfoSync();
        windowWidth = res.windowWidth - 32;//减掉的是容器的左右padding
      } catch (e) {
        console.error('getSystemInfoSync failed!');
      }
      //获取档案数据
      //获取最近一次测评记录的年月
      this.getData();
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
}))